package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import com.itheima.utils.HealthStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisPool;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wgq
 * @date 2019-10-11 11:15
 * 套餐服务管理
 */
@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;
    /*@Autowired
    private JedisPool jedisPool;*/

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired(required = false)
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setHashValueSerializer(stringSerializer);
        this.redisTemplate = redisTemplate;
    }

    /**
     * 分页查询套餐列表
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        if(null == currentPage || currentPage.intValue()<=0){
            currentPage =1;
        }
        Integer pageSize = queryPageBean.getPageSize();
        if(null == pageSize || pageSize.intValue() <= 0){
            pageSize = 10;
        }
        String queryString = queryPageBean.getQueryString();
        if(HealthStringUtils.isEmpty(queryString)){
            queryString = "";
        }else{
            queryString = queryString.trim();
        }
        PageHelper.startPage(currentPage, pageSize);
        System.out.println("queryString:"+queryString);
        Page<Setmeal> page = setmealDao.findByCondition("%"+queryString+"%");
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 新增套餐选项 ，判断新增套餐是否已经存在 和 关联检查组的提交.....
     * @param setmeal
     * @param checkgroupIds
     */
    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        if(setmealDao.findSetMealByCode(setmeal.getCode())>0){
            throw new RuntimeException("套餐编码已存在");
        }
        if(setmealDao.findSetMealByName(setmeal.getName()) >0){
            throw new RuntimeException("套餐名称已存在");
        }
        setmealDao.addSetMeal(setmeal);
        setSetMealAndCheckGroup(setmeal.getId(), checkgroupIds);

        // 这里注释掉 jedisPool ，为了使用RedisTemplate
        //jedisPool.getResource().sadd(RedisConstant.SEMEAL_PIC_DB_RESOURCES,setmeal.getImg());
        //这里为了使用注解格式的定时清理redis，所以改用 RedisTemplate这个配置
        redisTemplate.opsForSet().add(RedisConstant.SEMEAL_PIC_DB_RESOURCES, setmeal.getImg());
    }

    /**
     * 删除套餐服务
     * @param id
     */
    @Override
    public void delete(Integer id) {
        setmealDao.deleteCheckGroupIds(id);
        String sName = setmealDao.findById(id).getImg();
        //查看redis中的 setmealPicDbResources 是否含有数据库中查出来的该 图片名，有就删除
        /*if(redisTemplate.opsForSet().isMember(RedisConstant.SEMEAL_PIC_DB_RESOURCES,sName)) {
            redisTemplate.boundSetOps(RedisConstant.SEMEAL_PIC_DB_RESOURCES).remove(sName);
        }*/
        setmealDao.deleteSetMeal(id);
    }

    /**
     * 编辑套餐数据，根据行ID来查询套餐数据进行回显
     * @param id
     */
    @Override
    public Setmeal findById(Integer id) {
        Setmeal setmeal = setmealDao.findById(id);
        return setmeal;
    }

    /**
     * 根据当前行套餐ID，查询出关联的检查组ID列表，并进行回显
     * @param id
     * @return
     */
    @Override
    public List<Integer> findCheckGroupIdsBySetMealId(Integer id) {
        List<Integer> checkGroupList = setmealDao.findGroupIdsBySetMealId(id);
        return checkGroupList;
    }

    /**
     * 编辑套餐数据
     * @param setmeal
     */
    @Override
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        if(setmealDao.findSetMealName(setmeal)>0){
            throw  new RuntimeException("套餐组名称已存在，请修改.....");
        }
        setmealDao.deleteCheckGroupIds(setmeal.getId());
        setSetMealAndCheckGroup(setmeal.getId(),checkgroupIds);
        String sName = setmealDao.findById(setmeal.getId()).getImg();
        //查看redis中的 setmealPicDbResources 是否含有数据库中查出来的旧图片名。有就删除
        /*if(redisTemplate.opsForSet().isMember(RedisConstant.SEMEAL_PIC_DB_RESOURCES,sName)) {
            redisTemplate.boundSetOps(RedisConstant.SEMEAL_PIC_DB_RESOURCES).remove(sName);
        }*/
        setmealDao.editSetMeal(setmeal);
        //查看redis中的 setmealPicDbResources 是否含有 修改后的图片名。没有就添加到Redis
        redisTemplate.opsForSet().add(RedisConstant.SEMEAL_PIC_DB_RESOURCES, setmeal.getImg());
    }

    /**
     * 移动端，获取所有的套餐数据，用于回显
     * @return
     */
    @Override
    public List<Setmeal> getAllSetmeal() {
        return setmealDao.findAllSetmeal();
    }

    /**
     *  移动端， 根据套餐 ID 获取某一条套餐数据，用于移动端预约回显
     * @param id
     * @return
     */
    @Override
    public Setmeal findSetMealById(Integer id) {
        return setmealDao.findSetMealById(id);
    }

    /**
     * 查询套餐名称和预约套餐的人数
     *          [
     *           {"name":"套餐1","value":10},
     *           {"name":"套餐2","value":30},
     *           {"name":"套餐3","value":25}
     *          ]
     * @return
     */
    @Override
    public Map<String, Object> findSetmealCount() {
           /*[
            {"name":"套餐1","value":10},
            {"name":"套餐2","value":30},
            {"name":"套餐3","value":25}
           ]*/
        List<Map<String, Object>> list = setmealDao.findSetmealCount();
        //创建最外层，data的 map集合
        Map<String, Object> map = new HashMap<>();
        map.put("setmealCount", list);
        // "setmealNames":["套餐1","套餐2","套餐3"]
        List<String> setmealNames = new ArrayList<>();
        for (Map<String, Object> m : list) {
            String name = (String) m.get("name");
            setmealNames.add(name);
        }
        map.put("setmealNames", setmealNames);
        return map;
    }

    /**
     * 设置套餐和检查组之间的关联关系
     * @param setMealId
     * @param checkgroupIds
     */
    private void setSetMealAndCheckGroup(Integer setMealId, Integer[] checkgroupIds) {
        if (checkgroupIds != null && checkgroupIds.length>0){
            for (Integer checkgroupId : checkgroupIds) {
                setmealDao.setSetMealAndCheckGroup(setMealId, checkgroupId);
            }
        }
    }
}
